package com.ouyu.factory.support;

import com.ouyu.factory.config.BeanDefinition;
import com.ouyu.factory.exception.BeansException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @program: trySpring
 * @description: strategy impl jdk
 * @author: hz21056677
 * @create: 2021-08-05 15:56
 **/
public class SimpleInstantiationStrategy implements InstantiationStrategy{

    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) {
        //beanDefinition获取class信息
        final Class<?> clazz = beanDefinition.getBeanClass();
        try {
            if (null != ctor) {
                //有参构造函数
                return clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            }else{
                //无参构造函数
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
           throw new BeansException("Failed to instantiate[" + clazz.getName() + "]", e);
        }
    }
}
